<template>
  <div class="pad-20 bgc-default" v-loading="fullLoading" element-loading-text="加载中">
    <div class="pad-20 bg-color-white">
      <!-- 顶部按钮 -->
      <div>
        <template
          v-if="warehouseObj.warehouseType === 1 || warehouseObj.warehouseType === 2 || warehouseObj.warehouseType === 3">
          <el-button v-if="stockData.stockStatus == 0" type="primary" @click="doEditStock">编辑</el-button>
          <el-button v-if="stockData.stockStatus == 0" type="primary" @click="doSubmitStock">提交</el-button>
          <el-button v-if="warehouseObj.warehouseType == 1 && stockData.stockStatus == 1" type="primary"
            @click="doAuditStock">审核</el-button>
          <el-button v-if="stockData.stockStatus == 1" @click="doRevokeStock">撤销提交</el-button>
          <el-button
            v-if="warehouseObj.warehouseType == 1 && stockData.stockStatus == 0 && (stockData.businessType == 5 || stockData.businessType == 10)"
            type="primary" @click="doCopyStock">复制</el-button>
        </template>
        <el-button @click="doBack">返回上一级</el-button>
      </div>
      <!-- 出入库单详细信息 -->
      <div class="info-top-col">
        <el-row :gutter="20" class="mar-t-20">
          <el-col :span="12">
            <ul>
              <li class="flex">
                <label class="text-align-r">出入库单号：</label>
                <span>{{ stockData.stockNo }}</span>
                <span>({{ dict.stockStatus[stockData.stockStatus] }})</span>
              </li>
              <li class="flex">
                <label class="text-align-r">业务属性：</label>
                <span>{{ dict.businessType[stockData.businessType] }}</span><span
                  :class="stockData.stockChangeType==1 ? 'font-blue' : 'font-red'">({{ dict.stockChangeType[stockData.stockChangeType] }})</span>
              </li>
              <li class="flex">
                <label class="text-align-r">来源类型：</label>
                <span>{{ dict.stockSource[stockData.stockSource] }}</span>
              </li>
              <li class="flex">
                <label class="text-align-r">备注：</label>
                <span>{{ stockData.remark }}</span>
              </li>
            </ul>
          </el-col>
          <el-col :span="12">
            <ul>
              <li class="flex">
                <label class="text-align-r">仓库：</label>
                <span>{{ warehouseObj.warehouseName }}</span>
              </li>
              <li class="flex">
                <label class="text-align-r">供应商：</label>
                <span>{{ stockData.supplierName ? stockData.supplierName : '不限' }}</span>
              </li>
              <li class="flex">
                <label class="text-align-r">来源单号：</label>
                <span>{{ stockData.stockSourceNo }}</span>
              </li>
              <li class="flex">
                <label class="text-align-r">审核意见：</label>
                <span>{{ stockData.auditRemark }}</span>
              </li>
            </ul>
          </el-col>
        </el-row>
      </div>

      <!-- 搜索框 -->
      <div class="top-operate-default mar-t-20 pad-l-20">
        <div class="inline-flex">
          <el-select class="width-120" v-model="textCol">
            <el-option label="商品货号" value="goodsCode"></el-option>
            <el-option label="商品条码" value="goodsBarCode"></el-option>
            <el-option label="商品名称" value="title"></el-option>
          </el-select>
          <el-input @keyup.enter.native="doSearch" v-model.trim="textValue" placeholder="请输入内容" class="width-200">
          </el-input>
        </div>
        <el-cascader v-model="categoryIds" placeholder="选择商品分类" :options="categoryData" :props="{ checkStrictly: true }"
          class="pad-l-10" clearable filterable></el-cascader>
        <!-- 供应商 -->
        <el-select placeholder="供应商" v-model="defaultQuery.supplierId" class="pad-l-10" clearable>
          <el-option label="不限" value="0"></el-option>
          <el-option v-for="(item, index) in supplierList" :key="index" :label="item.supplierName"
            :value="item.supplierId"></el-option>
        </el-select>
        <el-button-group class="mar-l-20">
          <el-button type="primary" @click="doSearch">查询</el-button>
          <el-button plain @click="doResetSearch">重置</el-button>
        </el-button-group>
      </div>

      <div
        v-if="warehouseObj.warehouseType === 1 || warehouseObj.warehouseType === 2 || warehouseObj.warehouseType === 3">
        <div v-if="stockData.stockStatus == 0" class="flex mar-t-20">
          <!--产品说功能先隐藏<el-button type="primary" v-if="stockData.businessType == 5 || stockData.businessType == 10" @click="doOpenImport">导入</el-button>-->
          <el-input class="width-300 mar-l-20" v-model.trim="goodsBarCodeForm.goodsBarCode" placeholder="请输入待添加商品条码">
          </el-input>
          <el-button type="primary" @click="doSearchByBarCode">添加</el-button>
          <el-button type="primary" @click="doOpenGoodsSelect">查询添加</el-button>
          <el-button v-if="stockData.stockStatus == 0" @click="batchDelete">批量删除</el-button>
        </div>
      </div>

      <!-- 内容列表 -->
      <div class="table-container mar-t-20">
        <el-table :data="dataList" @selection-change="handleSelectionChange" v-loading="listLoading"
          element-loading-text="加载中">
          <el-table-column width="50px" type="selection" fixed="left"></el-table-column>
          <el-table-column min-width="320px" label="商品名称" prop="title">
            <template slot-scope="scope">
              <div class="v-align-c cursor-p">
                <label><img :src="scope.row.mainImage" class="t-goods-pic"></label>
                <div class="pad-l-10">
                  <div class="line-2 width-200">
                    <span class="font-blue" :title="scope.row.title">{{ scope.row.title }}</span>
                  </div>
                  <div>
                    <span>条码：{{ scope.row.goodsBarCode }}</span>
                    <span class="font-color-6 font-13"
                      v-if="scope.row.categoryName">[{{ scope.row.categoryName }}]</span>
                  </div>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column width="180px" label="规格描述" prop="skuDetail" align="center"></el-table-column>
          <el-table-column width="180px" label="数量" prop="goodsNum" align="center"></el-table-column>
          <el-table-column v-if="stockData.businessType == 5" width="180px" label="单价" align="center">
            <template slot-scope="scope">
              <div>{{scope.row.warehouseGoodsPrice}}</div>
              <div v-if="scope.row.taxFlag == 1">(已含税)</div>
              <div v-if="scope.row.taxFlag == 0">(未含税)</div>
            </template>
          </el-table-column>
          <el-table-column v-if="stockData.businessType == 5" width="180px" label="金额" align="center">
            <template slot-scope="scope">
              <div>￥{{ scope.row.warehouseGoodsAmount }}</div>
            </template>
          </el-table-column>
          <el-table-column v-if="stockData.businessType == 5" width="180px" label="税额" align="center">
            <template slot-scope="scope">
              <div>{{scope.row.taxPrice}}</div>
              <div>({{scope.row.taxRate}}%)</div>
            </template>
          </el-table-column>
          <el-table-column v-if="stockData.businessType == 5" width="180px" label="价税合计" align="center">
            <template slot-scope="scope">
              ￥{{ scope.row.warehouseGoodsAmountWithTax }}
            </template>
          </el-table-column>
          <el-table-column width="120px" label="供应商" prop="supplierName" align="center">
            <template slot-scope="scope">
              {{ scope.row.supplierName ? scope.row.supplierName : '(无)'}}
            </template>
          </el-table-column>
          <el-table-column min-width="240px" label="操作" fixed="right" align="right">
            <template slot-scope="scope">
              <template
                v-if="warehouseObj.warehouseType === 1 || warehouseObj.warehouseType === 2 || warehouseObj.warehouseType === 3">
                <el-button type="text" v-if="stockData.stockStatus == 0" size="medium" @click="doEdit(scope.row)">编辑
                </el-button>
                <el-button type="text" v-if="stockData.stockStatus == 0" size="medium" @click="doDelete(scope.row)">删除
                </el-button>
              </template>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 列表分页 -->
      <div class="pagination">
        <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page="searchListQuery.currentPage" :page-sizes="[10, 20, 50, 100]" :page-size="searchListQuery.size"
          layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>
      </div>
    </div>

    <!-- 出入库单dialog -->
    <el-dialog title="编辑出入库单" :visible.sync="stockEditVisible" width="580px">
      <warehouse-stock-edit :showFlag="stockEditVisible" :stockOrder="stockData" @callback="doCallbackEditStock">
      </warehouse-stock-edit>
    </el-dialog>

    <!-- 其他出入库 编辑商品dialog -->
    <el-dialog title="编辑商品（其他出入库）" :visible.sync="otherGoodsVisible" width="480px">
      <el-form ref="stockGoodsForm" :model="stockGoodsForm" :rules="rules" label-width="130px"
        class="mar-l-20 mar-r-20">
        <!-- 入库单 -->
        <div v-if="stockData.businessType == '5'">
          <el-form-item label="入库数量：" prop="goodsNum">
            <el-input v-model="stockGoodsForm.goodsNum"
              @keyup.native="stockGoodsForm.goodsNum = checkInputPositiveNum(stockGoodsForm.goodsNum)"></el-input>
          </el-form-item>
          <el-form-item label="单价：" prop="warehouseGoodsPrice">
            <div class="inline-flex">
              <el-select v-model="stockGoodsForm.taxFlag">
                <el-option label="已含税" value='1'></el-option>
                <el-option label="未含税" value='0'></el-option>
              </el-select>
              <el-input v-model="stockGoodsForm.warehouseGoodsPrice"></el-input>
            </div>
          </el-form-item>
        </div>
        <!-- 出库单 -->
        <div v-if="stockData.businessType == '10'">
          <el-form-item label="最大可出库数量：">
            <span>{{ stockGoodsNumForm.remainStock }}</span>
          </el-form-item>
          <el-form-item label="出库数量：" prop="goodsNum">
            <el-input v-model="stockGoodsForm.goodsNum"
              @keyup.native="stockGoodsForm.goodsNum = checkInputPositiveNum(stockGoodsForm.goodsNum)"></el-input>
          </el-form-item>
        </div>
      </el-form>
      <div class="dialog-footer mar-b-10">
        <el-button type="primary" @click="doSaveStockGoods">保存</el-button>
        <el-button @click="otherGoodsVisible = false">取消</el-button>
      </div>
    </el-dialog>

    <!-- 采购入库 编辑商品dialog -->
    <el-dialog title="编辑商品（采购入库）" :visible.sync="purchaseGoodsVisible" width="480px">
      <el-form ref="stockGoodsForm" :model="stockGoodsForm" :rules="rules" label-width="130px"
        class="mar-l-20 mar-r-20">
        <el-form-item label="未入库数量：">
          <span v-if="isEditGoods">{{stockGoodsNumForm.finalNum}}</span>
          <span v-else>{{stockGoodsNumForm.inputNum}}</span>
        </el-form-item>
        <el-form-item label="最大可入库数量：">
          <span
            v-if="isEditGoods">{{ (stockGoodsNumForm.finalNum - stockGoodsForm.goodsNum) > 0 ? stockGoodsNumForm.finalNum - stockGoodsForm.goodsNum : 0 }}</span>
          <span
            v-else>{{ (stockGoodsNumForm.inputNum - stockGoodsForm.goodsNum) > 0 ? stockGoodsNumForm.inputNum - stockGoodsForm.goodsNum : 0 }}</span>
          <span>（最大可入库数量=未入库数量－当前入库单已添加数量）</span>
        </el-form-item>
        <el-form-item label="入库数量：" prop="goodsNum">
          <el-input v-model="stockGoodsForm.goodsNum"
            @keyup.native="stockGoodsForm.goodsNum = checkInputPositiveNum(stockGoodsForm.goodsNum)"></el-input>
        </el-form-item>
      </el-form>
      <div class="dialog-footer mar-b-10">
        <el-button type="primary" @click="doSaveStockGoods">保存</el-button>
        <el-button @click="purchaseGoodsVisible = false">取消</el-button>
      </div>
    </el-dialog>

    <!-- 采购退退货 编辑商品dialog -->
    <el-dialog title="编辑商品（采购退货）" :visible.sync="purchaseReturnGoodsVisible" width="480px">
      <el-form ref="stockGoodsForm" :model="stockGoodsForm" :rules="rules" label-width="130px"
        class="mar-l-20 mar-r-20">
        <el-form-item label="未出库数量：">
          <span>{{stockGoodsNumForm.outputNum}}</span>
        </el-form-item>
        <el-form-item label="最大可出库数量：">
          <!-- <span>{{stockGoodsNumForm.outputNum}}</span> -->
          <span>{{ (stockGoodsNumForm.outputNum - stockGoodsForm.goodsNum) > 0 ? stockGoodsNumForm.outputNum - stockGoodsForm.goodsNum : 0 }}</span>
          <span>（最大可出库数量=未出库数量－当前出库单已添加数量）</span>
        </el-form-item>
        <el-form-item label="出库数量：" prop="goodsNum">
          <el-input v-model="stockGoodsForm.goodsNum"
            @keyup.native="stockGoodsForm.goodsNum = checkInputPositiveNum(stockGoodsForm.goodsNum)"></el-input>
        </el-form-item>
      </el-form>
      <div class="dialog-footer mar-b-10">
        <el-button type="primary" @click="doSaveStockGoods">保存</el-button>
        <el-button @click="purchaseReturnGoodsVisible = false">取消</el-button>
      </div>
    </el-dialog>

    <!-- 选择仓库商品dialog -->
    <el-dialog title="选择仓库商品" :visible.sync="warehouseGoodsSelectVisible" width="1200px" top="6vh">
      <warehouse-goods-sku-select :showFlag="warehouseGoodsSelectVisible" :warehouseId="stockData.warehouseId"
        :supplierId="stockData.supplierId" :warehouseGoodsIds="warehouseGoodsIds"
        :purchaseOrderNo="warehouseGoodsForm.purchaseOrderNo"
        :relationPurchaseOrderNo="warehouseGoodsForm.relationPurchaseOrderNo" :businessType="stockData.businessType"
        @addGoods="doAddGoods" @closeDialog="doCloseGoodsSelect">
      </warehouse-goods-sku-select>
    </el-dialog>

    <!-- 审核dialog -->
    <el-dialog width="500px" title="出入库单审核" :visible.sync="auditVisible">
      <div v-loading="fullLoading">
        <el-form ref="auditForm" :model="auditForm" label-width="120px" style="width: 460px">
          <el-form-item label="审核结果：" prop="stockStatus">
            <el-radio-group v-model="auditForm.stockStatus">
              <el-radio :label="2">审核通过</el-radio>
              <el-radio :label="3">审核不通过</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="审核意见：">
            <el-input type="textarea" :rows="3" v-model="auditForm.auditRemark"></el-input>
          </el-form-item>
        </el-form>
        <div class="dialog-footer mar-b-10">
          <el-button type="primary" @click="doSaveAudit">确定</el-button>
          <el-button @click="auditVisible = false">取消</el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 导入dialog -->
    <el-dialog width="500px" title="导入出入库单商品明细" :visible.sync="importStockGoodsVisible">
      <div v-loading="importLoading">
        <el-form :model="importForm" label-width="130px">
          <el-form-item label="导入文件：">
            <div v-if="importForm.importFileName">{{ importForm.importFileName }}</div>
            <el-upload name="files" action="/api/common/uploadFiles" :multiple="false" :show-file-list="false"
              :data="token" :before-upload="beforeUploadFile" :on-success="handleUploadSuccess">
              <el-button size="small" type="primary">选取文件</el-button>
            </el-upload>
            <span class="font-blue">
              <el-button @click="doDownloadTemplate" type="text">下载导入模板</el-button>
            </span>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="doImport">确定</el-button>
          <el-button @click="importStockGoodsVisible = false">取消</el-button>
        </div>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import {
    getWarehouse
  } from '@/api/warehouse/warehouseInfo'
  import {
    getOrderGoods
  } from '@/api/warehouse/purchaseOrder'
  import {
    listSupplier
  } from '@/api/user/supplier'
  import {
    getDictByGroupName,
    downloadFile
  } from '@/api/common/common'
  import {
    listGoodsCategory
  } from '@/api/goods/goods'
  import {
    getToken
  } from '@/utils/auth'
  import {
    getStock,
    getByBarCode,
    saveStockGoods,
    doSubmit,
    copyStock,
    doAudit,
    doRevoke,
    doImportGoods,
    batchDeleteStockGoods
  } from '@/api/warehouse/warehouseStock'
  import {
    pagingStockGoods
  } from '@/api/warehouse/warehouseStockGoods'
  import warehouseGoodsSkuSelect from '@/views/warehouse/components/warehouse-goods-sku-select'
  import warehouseStockEdit from '../../components/warehouse-stock-edit'

  export default {
    components: {
      warehouseGoodsSkuSelect,
      warehouseStockEdit
    },
    data() {
      const validateNum = (rule, value, callback) => {
        const flag = this.validatePositiveNum(value)
        if (!flag || value <= 0) {
          callback(new Error('请输入大于0整数'))
          return
        }
        callback()
      }
      return {
        // 商品分类model
        categoryIds: [],
        // 文本model
        textCol: 'goodsCode',
        textValue: '',
        // 查询条件
        searchListQuery: {},
        // 默认条件
        defaultQuery: {
          currentPage: 1,
          size: 10,
          supplierId: ''
        },
        // 仓库信息
        warehouseObj: {
          warehouseType: ''
        },
        // 出入库单信息
        stockData: {
          stockId: '',
          stockSource: '',
          stockStatus: '',
          stockChangeType: ''
        },
        // 供应商列表
        supplierList: [],
        // 数据字典
        dict: {
          businessType: {},
          stockSource: {},
          stockStatus: {},
          stockChangeType: {}
        },
        // 商品分类集合
        categoryData: [],
        total: 0,
        // 勾选集合
        multipleSelection: [],
        dataList: [],
        // 页面loading
        fullLoading: false,
        // 列表loading
        listLoading: false,
        isEditGoods: false,
        // 其他出入库 商品编辑dialog
        otherGoodsVisible: false,
        // 采购入库 商品编辑dialog
        purchaseGoodsVisible: false,
        // 采购退货 商品编辑dialog
        purchaseReturnGoodsVisible: false,
        // 多个商品dialog
        warehouseGoodsSelectVisible: false,
        // 出入库单dialog
        stockEditVisible: false,
        // 审核弹窗
        auditVisible: false,
        // 导入商品明细
        importStockGoodsVisible: false,
        importLoading: false,
        // 仓库商品表单
        warehouseGoodsForm: {
          purchaseOrderNo: '',
          relationPurchaseOrderNo: ''
        },
        // 编辑出入库单商品表单
        stockGoodsForm: {
          stockId: '',
          stockGoodsId: '',
          warehouseGoodsId: '',
          warehouseGoodsPrice: '',
          goodsNum: 0, // 商品数量
          taxRate: '',
          taxFlag: '0', // 是否含税
          isEditPurchaseGoods: false, // 是否编辑采购单商品
          stockSource: '0' // 出入库单来源
        },
        // 获通过商品条形码获取仓库商品表单
        goodsBarCodeForm: {
          warehouseId: '',
          goodsBarCode: '',
          supplierId: '',
          stockSource: '0',
          stockSourceNo: ''
        },
        // 审核数据
        auditForm: {
          stockId: '',
          auditStatus: 2,
          auditRemark: ''
        },
        // 仓库商品id集合
        warehouseGoodsIds: [],
        // 出入库数量查验对象
        stockGoodsNumForm: {
          remainStock: 0, // 最大可出库数量
          inputNum: 0, // 未入库数量
          outputNum: 0, // 未出库数量
          finalNum: 0
        },
        // 导入的表单
        importForm: {},
        token: '',
        rules: {
          goodsNum: [{
            required: true,
            message: '请输入数量',
            trigger: 'blur'
          }, {
            'validator': validateNum,
            'trigger': 'blur'
          }]
        }
      }
    },
    created() {
      this.searchListQuery = {
        ...this.defaultQuery
      }
      this.token = {
        accessToken: getToken()
      }
      // 获取零售商品分类
      listGoodsCategory(this.getEnterpriseId()).then(response => {
        this.categoryData = response.data
      })
      // 获取数据字典
      getDictByGroupName('WarehouseStockDTO').then(response => {
        this.dict = response.data
      })
      // 获取仓库信息
      getWarehouse(this.getWarehouseId()).then((response) => {
        if (response.isError) return
        Object.assign(this.warehouseObj, response.data)
      })
      this.listSupplier()
      const queryParams = this.getCurrentPage().query
      if (queryParams && queryParams.stockId) {
        this.stockData.stockId = queryParams.stockId
        this.init()
        this.initList()
      }
    },
    methods: {
      // 初始化
      init() {
        this.fullLoading = true
        getStock(this.stockData.stockId).then(response => {
          this.fullLoading = false
          this.stockData = response.data
          this.warehouseGoodsForm.relationPurchaseOrderNo = this.stockData.stockSourceNo
          if (this.stockData.stockSource === 1) {
            this.warehouseGoodsForm.purchaseOrderNo = this.stockData.stockSourceNo
          }
        })
      },
      // 初始化列表
      initList() {
        this.listLoading = !this.fullLoading
        const size = this.searchListQuery.size
        const currentPage = this.searchListQuery.currentPage
        this.searchListQuery = {
          ...this.defaultQuery
        }
        this.searchListQuery.size = size
        this.searchListQuery.currentPage = currentPage
        this.searchListQuery[this.textCol] = this.textValue
        this.searchListQuery.oneCategoryId = this.categoryIds.length > 0 ? this.categoryIds[0] : ''
        this.searchListQuery.twoCategoryId = this.categoryIds.length > 1 ? this.categoryIds[1] : ''
        this.searchListQuery.threeCategoryId = this.categoryIds.length > 2 ? this.categoryIds[2] : ''
        this.searchListQuery.stockId = this.stockData.stockId
        if (this.searchListQuery.supplierId === '0') {
          this.searchListQuery.supplierId = ''
        }
        pagingStockGoods(this.searchListQuery).then(response => {
          this.listLoading = false
          if (response.isError) return
          this.dataList = response.data.records
          this.total = response.data.total
        })
      },
      // 编辑事件
      doEditStock() {
        this.stockEditVisible = true
      },
      // 关闭出入库dialog事件
      doCallbackEditStock(callbackFlag) {
        if (callbackFlag) {
          this.init()
        }
        this.stockEditVisible = false
      },
      // 提交事件
      doSubmitStock() {
        this.fullLoading = true
        doSubmit(this.stockData.stockId).then(response => {
          if (response.isError) {
            this.fullLoading = false
            return
          }
          this.$message({
            type: 'success',
            message: '提交成功'
          })
          this.init()
        })
      },
      // 撤销提交事件
      doRevokeStock() {
        this.fullLoading = true
        doRevoke(this.stockData.stockId).then(response => {
          if (response.isError) {
            this.fullLoading = false
            return
          }
          this.$message({
            type: 'success',
            message: '撤销提交成功'
          })
          this.init()
        })
      },
      // 复制事件
      doCopyStock() {
        this.fullLoading = true
        copyStock(this.stockData.stockId).then(response => {
          if (response.isError) {
            this.fullLoading = false
            return
          }
          this.$message({
            type: 'success',
            message: '复制成功'
          })
          this.doBack()
        })
      },
      // 返回事件
      doBack() {
        this.$router.go(-1)
      },
      // 审核事件
      doAuditStock() {
        this.auditVisible = true
      },
      // 审核确定事件
      doSaveAudit() {
        this.fullLoading = true
        this.auditForm.stockId = this.stockData.stockId
        doAudit(this.auditForm).then(response => {
          if (response.isError) {
            this.fullLoading = false
            return
          }
          this.$message({
            type: 'success',
            message: '审核成功'
          })
          this.init()
          this.auditVisible = false
        })
      },
      // 根据商品条码添加事件
      doSearchByBarCode() {
        if (!this.goodsBarCodeForm.goodsBarCode) {
          this.$message({
            type: 'error',
            message: '请填写或扫描商品条码!'
          })
          return
        }
        this.listLoading = true
        this.goodsBarCodeForm.warehouseId = this.stockData.warehouseId
        this.goodsBarCodeForm.supplierId = this.stockData.supplierId
        this.goodsBarCodeForm.stockSource = this.stockData.stockSource
        this.goodsBarCodeForm.stockSourceNo = this.stockData.stockSourceNo
        getByBarCode(this.goodsBarCodeForm).then(response => {
          this.listLoading = false
          if (response.isError) return
          const data = response.data
          this.stockGoodsForm.stockSource = this.stockData.stockSource
          this.stockGoodsForm.stockSourceNo = this.stockData.stockSourceNo
          // 查到一笔
          if (data.length === 1) {
            const form = {
              warehouseGoodsId: data[0]
            }
            this.doAddGoods(form)
            return
          }
          // 查到多笔
          if (data.length > 1) {
            this.warehouseGoodsIds = data
            this.warehouseGoodsSelectVisible = true
            return
          }
          this.$message({
            type: 'error',
            message: '未找到指定的商品，请重新填写或扫码!'
          })
        })
      },
      // 查询事件
      doSearch() {
        this.searchListQuery.currentPage = 1
        this.initList()
      },
      // 重置事件
      doResetSearch() {
        this.searchListQuery = {
          currentPage: 1,
          size: 10,
          stockId: '',
          warehouseId: '',
          supplierId: '',
          oneCategoryId: '',
          twoCategoryId: '',
          threeCategoryId: ''
        }
        this.defaultQuery.supplierId = ''
        this.textCol = 'goodsCode'
        this.textValue = ''
        this.categoryIds = []
        this.initList()
      },
      // 获取采购单商品库存
      getPurchaseOrderStock(purchaseOrderNo, warehouseGoodsId) {
        const form = {
          purchaseOrderNo: purchaseOrderNo,
          warehouseGoodsId: warehouseGoodsId,
          stockId: this.stockData.stockId
        }
        getOrderGoods(form).then(response => {
          if (response.isError) return
          if (response.data.purchaseOrderType === 2) {
            this.stockGoodsNumForm.outputNum = response.data.notWarehouseOutNum
          }
          this.stockGoodsNumForm.inputNum = response.data.notStockInNum
          this.stockGoodsNumForm.finalNum = response.data.finalNum
        })
      },
      // 商品选择添加 回调事件
      doAddGoods(row) {
        this.stockGoodsForm = {
          warehouseGoodsId: row.warehouseGoodsId,
          taxFlag: row.supplierTaxFlag ? row.supplierTaxFlag + '' : '0',
          goodsNum: 0,
          warehouseGoodsPrice: row.supplyPrice
        }
        this.stockGoodsNumForm.remainStock = row.remainStock
        switch (this.stockData.businessType) {
          // 采购入库
          case 1:
            this.getPurchaseOrderStock(this.stockData.stockSourceNo, row.warehouseGoodsId)
            this.purchaseGoodsVisible = true
            break
            // 采购退货单
          case 6:
            this.getPurchaseOrderStock(this.stockData.stockSourceNo, row.warehouseGoodsId)
            this.purchaseReturnGoodsVisible = true
            break
          default:
            this.otherGoodsVisible = true
        }
      },
      // 编辑
      doEdit(row) {
        console.log(row)
        this.isEditGoods = true
        // 根据业务属性打开弹窗
        this.stockGoodsForm = {
          warehouseGoodsId: row.warehouseGoodsId,
          stockGoodsId: row.stockGoodsId,
          taxFlag: row.taxFlag.toString(),
          goodsNum: row.goodsNum,
          warehouseGoodsPrice: row.warehouseGoodsPrice,
          stockSource: this.stockData.stockSource,
          stockSourceNo: this.stockData.stockSourceNo
        }
        this.stockGoodsNumForm.remainStock = row.remainStock
        if (this.stockData.stockSource !== 0) {
          this.getPurchaseOrderStock(this.stockData.stockSourceNo, row.warehouseGoodsId)
        }
        switch (this.stockData.businessType) {
          // 采购入库
          case 1:
            // 采购入库
            this.purchaseGoodsVisible = true
            break
            // 采购退货单
          case 6:
            this.purchaseReturnGoodsVisible = true
            break
          default:
            this.otherGoodsVisible = true
        }
      },
      // 保存出入库单商品
      doSaveStockGoods() {
        const goodsNum = this.stockGoodsForm.goodsNum
        if (!goodsNum) {
          this.$message({
            type: 'error',
            message: '数量不能为空'
          })
          return
        }
        // 采购入库
        if (this.stockData.businessType === 1 && goodsNum > this.stockGoodsNumForm.inputNum && this.stockGoodsForm
          .stockGoodsId === undefined) {
          this.$message({
            type: 'error',
            message: '入库数量不得超过未入库数量'
          })
          return
        }
        // 采购入库
        if (this.stockData.businessType === 6 && goodsNum > this.stockGoodsNumForm.outputNum && !this.isEditGoods) {
          this.$message({
            type: 'error',
            message: '出库数量不得超过最大出库数'
          })
          return
        }
        // 其他出库
        if (this.stockData.businessType === 10 && goodsNum > this.stockGoodsNumForm.remainStock) {
          this.$message({
            type: 'error',
            message: '出库数量不得超过最大出库数' + this.stockGoodsNumForm.remainStock
          })
          return
        }
        // 其他入库
        if (this.stockData.businessType === 5 && this.stockGoodsForm.warehouseGoodsPrice * 1 === 0) {
          this.$confirm('商品单价为0，是否确认继续保存？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            title: '温馨提示',
            type: 'warning'
          }).then(() => {
            this.handleSaveStockGoods()
          }).catch(() => {})
        } else {
          this.handleSaveStockGoods()
        }
      },
      // 编辑商品保存事件
      handleSaveStockGoods() {
        this.listLoading = true
        this.stockGoodsForm.stockId = this.stockData.stockId
        this.stockGoodsForm.isEditPurchaseGoods = this.isEditGoods
        saveStockGoods(this.stockGoodsForm).then(response => {
          if (response.isError) {
            this.listLoading = false
            return
          }
          this.$message({
            type: 'success',
            message: '保存商品成功'
          })
          this.purchaseGoodsVisible = false
          this.purchaseReturnGoodsVisible = false
          this.otherGoodsVisible = false
          this.isEditGoods = false
          this.initList()
        })
      },
      // 删除关联商品
      doDelete(row) {
        const arr = []
        arr.push(row.stockGoodsId)
        const data = {
          stockId: this.stockData.stockId,
          stockGoodsIds: arr
        }
        this.listLoading = true
        batchDeleteStockGoods(data).then(response => {
          if (response.isError) {
            this.listLoading = false
            return
          }
          this.$message({
            type: 'success',
            message: '删除成功'
          })
          this.initList()
        })
      },
      // 批量删除关联商品
      batchDelete() {
        const selections = this.multipleSelection
        if (selections === undefined || selections.length === 0) {
          this.$message({
            type: 'error',
            message: '请选择商品'
          })
          return
        }
        const arr = []
        selections.forEach(e => {
          arr.push(e.stockGoodsId)
        })
        const data = {
          stockId: this.stockData.stockId,
          stockGoodsIds: arr
        }
        this.listLoading = true
        batchDeleteStockGoods(data).then(response => {
          if (response.isError) {
            this.listLoading = false
            return
          }
          this.$message({
            type: 'success',
            message: '批量删除成功'
          })
          this.initList()
        })
      },
      // 查询添加事件 打开商品选择dialog
      doOpenGoodsSelect() {
        this.warehouseGoodsIds = []
        this.warehouseGoodsSelectVisible = true
        this.isEditGoods = false
      },
      // 关闭商品选择dialog
      doCloseGoodsSelect() {
        this.warehouseGoodsSelectVisible = false
      },
      // 供应商列表
      listSupplier() {
        listSupplier({
          enterpriseId: this.getEnterpriseId()
        }).then(response => {
          if (response.isError) return
          this.supplierList = response.data
        })
      },
      // 打开导入dialog
      doOpenImport() {
        this.importForm = {
          fileUrl: '',
          importFileName: ''
        }
        this.importStockGoodsVisible = true
      },
      // 下载导入模板事件
      doDownloadTemplate() {
        downloadFile('https://enterpriseimg.joinsun.vip/upload/import_purchase_order_goods.xlsx', {}, '导入采购单商品明细')
      },
      // 文件上传前校验事件
      beforeUploadFile(file) {
        const ext = file.name.substring(file.name.lastIndexOf('.') + 1)
        if (ext !== 'xlsx') {
          this.$message.error('请上传xlsx格式的Excel')
          return false
        }
        this.importLoading = true
        return true
      },
      // 上传成功后事件
      handleUploadSuccess(res, file) {
        this.importLoading = false
        if (res.code !== 101) {
          this.$message.error(res.msg)
          return
        }
        this.importForm = {
          importFileName: file.name,
          fileUrl: res.data[0]
        }
        this.$message({
          type: 'success',
          message: '文件已上传'
        })
      },
      // 导入事件
      doImport() {
        if (!this.importForm.importFileName || !this.importForm.fileUrl) {
          this.$message({
            type: 'error',
            message: '请先上传文件'
          })
          return
        }
        this.importLoading = true
        this.importForm.stockId = this.stockData.stockId
        doImportGoods(this.importForm).then(response => {
          this.importLoading = false
          if (response.isError) return
          this.importStockGoodsVisible = false
          this.init()
          this.$message({
            type: 'success',
            message: '导入成功'
          })
        })
      },
      // 勾选事件
      handleSelectionChange(val) {
        this.multipleSelection = val
      },
      // 更改当前页数
      handleCurrentChange(val) {
        this.searchListQuery.currentPage = val
        this.initList()
      },
      // 更改当前页面大小
      handleSizeChange(val) {
        this.searchListQuery.size = val
        this.initList()
      }
    }
  }
</script>
